package it.unina.multimodal;

import it.unina.lab.config.Logger;
import it.unina.lab.costants.Constants;
import it.unina.lab.managers.Controller;
import it.unina.lab.modality.ModalityComponent;
import it.unina.lab.model.ActionHL;
import it.unina.lab.model.ModalityEvent;
import it.unina.lab.multimodal.R;

import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;

public class MainActivity extends Activity  {
    
	private Logger logger = Logger.getLogger();
	private ImageButton speech = null;
	private Button button_1 = null;
	private Button button_2 = null;
	private Button button_3 = null;
	private Button white_selection = null;
	private Button red_selection = null;
	//private Button rfid = null;
	private SpeechRecognizer speechRecognizer;
	private ModalityComponent speechM;
	private ModalityComponent touchM;
	private Controller controller;
	private Handler activityHandler;
	
	private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
	
	
	

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        speech = (ImageButton) findViewById(R.id.speech);
        button_1 = (Button) findViewById(R.id.button_1);
        button_2 = (Button) findViewById(R.id.button_2);
        button_3 = (Button) findViewById(R.id.button_3);
        white_selection = (Button) findViewById(R.id.white_selection);
        red_selection = (Button) findViewById(R.id.red_selection);
        //rfid = (Button) findViewById(R.id.rfid);

        
        
        /*
		 * Create the main handler on the main thread so it is bound to the main
		 * thread's message queue. 
		 */
        controller = Controller.getControllerIstance();
        controller.addOutboxHandler(activityHandler = new Handler() {
        	public void handleMessage(Message msg) {
        		
        		/* Handle the message coming from the Interaction Manager Thread */
        		logger.info("Got an incoming message from the Interaction Manager thread: " + msg);
        		ActionHL data = (ActionHL) msg.obj;
        		String colore = (String) data.getVariabili().get("task");
        		String colore_t = (String) data.getVariabili().get("color");
        		String bottone_id = (String) data.getVariabili().get("bottone");
        		
        		if((colore!= null && colore.equalsIgnoreCase("rosso")) | (colore_t!=null && colore_t.equalsIgnoreCase("r")))
        			findViewById((int)(Integer.valueOf(bottone_id))).setBackgroundColor(Color.RED);
        		else if((colore!= null && colore.equalsIgnoreCase("bianco")) | (colore_t!=null && colore_t.equalsIgnoreCase("w")))
        			findViewById((int)(Integer.valueOf(bottone_id))).setBackgroundColor(Color.WHITE);
        		
        		/* task - bottone */
        		/*Bundle bundle = msg.getData();
	    		if(bundle.containsKey(Constants.MESSAGE_APP_ACTION)){
	    			testo.setText(bundle.getString(Constants.MESSAGE_APP_ACTION)); 
	    			
	    		} */
        	}
        });
        
        
		
        try {
			speechM = new SpeechModality("speech", controller, speech);
			touchM = new TouchModality("touch", controller);
			touchM.register();
			speechM.register();
			
			speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
			speechRecognizer.setRecognitionListener((RecognitionListener) speechM);
			
			InputStream is = this.getAssets().open(Constants.HEPHAISTK_SMUIML_FILE);
			Message msg = Message.obtain(controller.getInboxHandler(), Constants.MESSAGE_REGISTER_FINISH, is);
			msg.sendToTarget();
        } catch (IOException e) {
			logger.error("File xml non trovato o problemi nell'apertura", e);	
        }	
		
		
			
			
		speech.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
			        	//ModalityEvent event = new ModalityEvent(speechM.getName(), "task", "play");
						//speechM.sendEvent(event);
				startVoiceRecognitionActivity();
			}
		});
		
		
		
		
		button_1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
			        	ModalityEvent event = new ModalityEvent(touchM.getName(), "bottone", String.valueOf(button_1.getId()));
						touchM.sendEvent(event);
				
			}
		});
		
		
		button_2.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
			        	ModalityEvent event = new ModalityEvent(touchM.getName(), "bottone", String.valueOf(button_2.getId()));
						touchM.sendEvent(event);
				
			}
		});
		
		button_3.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
			        	ModalityEvent event = new ModalityEvent(touchM.getName(), "bottone", String.valueOf(button_3.getId()));
						touchM.sendEvent(event);
				
			}
		});
		
		
		white_selection.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
			        	ModalityEvent event = new ModalityEvent(touchM.getName(), "color", String.valueOf(white_selection.getText()));
						touchM.sendEvent(event);
				
			}
		});
		
		
		red_selection.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
			        	ModalityEvent event = new ModalityEvent(touchM.getName(), "color", String.valueOf(red_selection.getText()));
						touchM.sendEvent(event);
				
			}
		});
		
	/*	rfid.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
			        	ModalityEvent event = new ModalityEvent(rfidM.getName(), "task", "76687989");
						rfidM.sendEvent(event);
			}
		}); */
			
    }
    
    
    
    
    
    @Override
	protected void onDestroy() {
		controller.removeOutboxHandler(activityHandler);
		super.onDestroy();
	}





	/**
     * Fire an intent to start the speech recognition activity.
     */
    private void startVoiceRecognitionActivity() {
       /* Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speech recognition demo");
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "it-IT");
        startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE); */
    	
    	Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);        
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,"it.unina.multimodal");
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "it-IT");
        intent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS,true);
        intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,5); 
        speechRecognizer.startListening(intent);
    }

    /**
     * Handle the results from the recognition activity.
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
            // Fill the list view with the strings the recognizer thought it could have heard   
            speechM.sendEvent(new ModalityEvent(speechM.getName(), "task", data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS).get(0)));
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    
    
    
    
}